package com.lepu.app.fun.grow;

import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.mother_circle.adapter.AdapterMotherMessage;
import com.lepu.app.fun.mother_circle.bean.BeanMotherCircle;
import com.lepu.app.fun.mother_circle.bean.BeanMotherMessage;
import com.lepu.app.fun.my.bean.BeanMessage;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

public class GrowMessageActivity extends BaseFragmentActivity implements
        OnTopbarNewLeftLayoutListener, OnTopbarNewRightButtonListener,AsyncRequest {
	private static final String REQUEST_MSG = "request_msg";
	
    private ListView mDataListView = null;
    private AdapterMotherMessage mDataAdapter = null;
    private ArrayList<BeanMessage> mDataArrayList = null;


    private int mBoard = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
    	mNeedSwipeBack = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.grow_message_activity);
        init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 添加页面动画，需要重写这个方法，
     */
    @Override
    public void onBackPressed() {
    	BeanMessage.updateNewMessageRead(LoginUtil.getUserId(), mBoard);
        finish(true);
    }

    @Override
    public void onTopbarLeftLayoutSelected() {
    	BeanMessage.updateNewMessageRead(LoginUtil.getUserId(), mBoard);
        finish(true);
    }


    public void showHideNoDataLayout(boolean isShow) {
        LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
        if (noDataLayout != null) {
            if (isShow) {
                noDataLayout.setVisibility(View.VISIBLE);
            } else {
                noDataLayout.setVisibility(View.GONE);
            }
        }
    }

    public void showFirstLoadDataLayout(boolean isShow) {
        LinearLayout firstLoadDataLayout = (LinearLayout) findViewById(R.id.firstLoadDataLayout);
        if (firstLoadDataLayout != null) {
            if (isShow) {
                firstLoadDataLayout.setVisibility(View.VISIBLE);
            } else {
                firstLoadDataLayout.setVisibility(View.GONE);
            }
        }
    }
    
    @Override
    public void onTopbarRightButtonSelected() {
        deleteAllItem();
    }
    
    /**
     * 初始化方法
     */
    private void init() {
        // topbar
        CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
        topbar.setTopbarTitle("");
        topbar.setonTopbarNewLeftLayoutListener(this);

        Bundle data = this.getIntent().getExtras();
        if(data != null && data.size() > 0)
        {
            mBoard = data.getInt("type");
        }

        if(mBoard == 1){
        	  topbar.setTopbarTitle("热门相册消息");
        }else if(mBoard == 2){
        	  topbar.setTopbarTitle("妈妈圈消息");
        }

        mDataListView = (ListView) findViewById(R.id.dataListView);

        mDataListView.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view,
                                             int scrollState) {
                if (scrollState == 0) {
                    UniversalImageLoadTool.resume();
                } else {
                    UniversalImageLoadTool.pause();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
            }
        });

        refreshView();
        // 第一次进入页面获取数据
        requestAlarm();
    }

	/**
	 * 请求消息
	 */
	private void requestAlarm() {
		String url = Setting.getMassegeDataUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
		    params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			params.put("MessageType", mBoard);
		} catch (Exception e) {
			
		}
		map.put("ht", params);
		ApiClient.http_post_main(url, map, null, this, REQUEST_MSG, true);
	}
	
	@Override
	public void RequestComplete(Object object, Object data) {
		ArrayList<BeanMessage> beanList = BeanMessage.parseJsonData((String)data);
		for(BeanMessage item : beanList)
		{
			item.Board = mBoard;
			item.IsRead = 0;
			item.LoginUserID = LoginUtil.getUserId();
			BeanMessage.insertMyMessage(item);
		}
		
		refreshView();
	}

	@Override
	public void RequestError(Object arg0, int arg1, String arg2) {
		
	}
    
	private void refreshView(){
		mDataArrayList = BeanMessage.getMyMessage(LoginUtil.getUserId(), mBoard);
		if(mDataArrayList.size() == 0){
			showHideNoDataLayout(true);
			return;
		}else{
			showHideNoDataLayout(false);
			mDataAdapter = new AdapterMotherMessage(GrowMessageActivity.this, mDataArrayList);
			mDataListView.setAdapter(mDataAdapter);
		}
	}
	
	
    public void deleteItem(final int position, final int id) {
        new MyDialog(GrowMessageActivity.this)
                .setMessage("您确定删除当前消息吗?")
                .setNegativeButton(R.string.app_cancel,
                        new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {

                            }
                        })
                .setPositiveButton(R.string.app_ok,
                        new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {

                                String uid = MyApplication.getInstance().getLoginInfo().UserID;
                                BeanMotherMessage.deleteItem(uid, id);

                                mDataArrayList.remove(position);
                                mDataAdapter.notifyDataSetChanged();
                            }
                        }).create(null).show();
    }

    private void deleteAllItem() {
        if (mDataArrayList == null || mDataArrayList.size() == 0)
            return;

        new MyDialog(GrowMessageActivity.this)
                .setMessage("您确定清空消息列表吗?")
                .setNegativeButton(R.string.app_cancel,
                        new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {

                            }
                        })
                .setPositiveButton(R.string.app_ok,
                        new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {

                                String uid = MyApplication.getInstance().getLoginInfo().UserID;
                                BeanMotherMessage.deleteAllItem(uid, mBoard);

                                refreshView();
                                UIHelper.showToast(GrowMessageActivity.this, "清空消息列表成功");
                            }
                        }).create(null).show();
    }

}
